/*---------------------------------------------------------------------------------------------------------*/
/*                                                                                                         */
/* Copyright (c) Nuvoton Technology Corp. All rights reserved.                                             */
/*                                                                                                         */
/*---------------------------------------------------------------------------------------------------------*/
#include "HID_ISP.h"
#include "prog.h"
#include "EmAes.h"
uint32_t ISPRead(uint32_t addr);
/*----------------------------------------------------------------------------
  MAIN function
 *----------------------------------------------------------------------------*/
int32_t main(void)
{
    volatile uint32_t u32INTSTS;
    
    UNLOCKREG();
	
	/* Initialize device ISP environment */
    udcFlashInit();  
    
    /* Check if GPB15 is low */
	/* GPB15 is key 1 on 120 board */
	if ( ( ISPRead(APP_FLAG_ADDR) ==  APP_VALID  )
      && ( (inp32(GPIOB_BASE + 0x10) & BIT15) != 0)
	  && (! IsUserReset())
		 )
    {
		ClearUserReset();
        /* Boot from AP */
		if(FMC->ISPCON.BS){
        	FMC->ISPCON.BS = 0;    
        	outp32(&SYS->IPRSTC1, 0x02);
        	while(1);
		}
    }
	ClearUserReset();

    /* Enable 12M Crystal */
    SYSCLK->PWRCON.XTL12M_EN = 1;
    RoughDelay(0x2000);                     

    /* Enable PLL */
    outp32(&SYSCLK->PLLCON, 0xC22E);
    RoughDelay(0x2000);

    /* Switch HCLK source to PLL */
    SYSCLK->CLKSEL0.HCLK_S = 2;
    
    /* Initialize USB Device function */

    /* Enable PHY to send bus reset event */
    _DRVUSB_ENABLE_USB();

    outp32(&USBD->DRVSE0, 0x01);
    RoughDelay(1000);
    outp32(&USBD->DRVSE0, 0x00);
    RoughDelay(1000);

    /* Disable PHY */
    _DRVUSB_DISABLE_USB();

    /* Enable USB device clock */
    outp32(&SYSCLK->APBCLK, BIT27);

    /* Reset IP */	
    outp32(&SYS->IPRSTC2, BIT27);
    outp32(&SYS->IPRSTC2, 0x0);	

    _DRVUSB_ENABLE_USB();
    outp32(&USBD->DRVSE0, 0x01);
    RoughDelay(1000);
    outp32(&USBD->DRVSE0, 0x00);

	g_u8UsbState = USB_STATE_DETACHED;
	_DRVUSB_TRIG_EP(1, 0x08);
	UsbFdt();
      
    /* Start USB HID */

    /* Handler the USB ISR by polling */
	while(1)
	{
	    u32INTSTS = _DRVUSB_GET_EVENT_FLAG();
	
        if (u32INTSTS & INTSTS_FLDET)
	    {
	        /* Handle the USB attached/detached event */
		    UsbFdt();
	    }
	    else if(u32INTSTS & INTSTS_BUS)
	    {
	        /* Handle the USB bus event: Reset, Suspend, and Resume */
		    UsbBus();
	    }
	    else if(u32INTSTS & INTSTS_USB)
	    {
	        /* Handle the USB Protocol/Clase event */
		    UsbUsb(u32INTSTS);
        }
	}
}



